<?php

if (isset($_REQUEST['term']) && $_REQUEST['term'] != "") {

  $query = sprintf("
    SELECT stock.symbol, stock.name AS stock_name, exchange.name AS exchange_name
    FROM stock
    JOIN exchange ON stock.exchange_id = exchange.id
    WHERE stock.symbol LIKE '%%%s%%'
      OR stock.name LIKE '%%%s%%'",
    mysql_real_escape_string($_REQUEST['term']), mysql_real_escape_string($_REQUEST['term']));
  
  if (!($results = mysql_query($query)) || mysql_num_rows($results) == 0) {
    
    throw new Exception("The search term \"". mysql_real_escape_string($_REQUEST['term']) ."\" returned no results.", 404);
  
  }
  
  if (mysql_num_rows($results) == 1) {
    $stock = mysql_fetch_assoc($results);
    header("Location: /details?symbol=". $stock['symbol']);
  }
  
} else {
  throw new Exception("Please enter a search term.", 400);
}

?>
      <header>
        <div class="row">
          <div class="span6">
            <h1>Search Results</h1>
            <table class="table table-bordered table-striped">
              <tbody>
                <tr>
                  <th>Symbol</th>
                  <th>Company Name</th>
                  <th>Exchange</th>
                </tr>
<?php while ($stock = mysql_fetch_assoc($results)) { ?>
                <tr>
                  <td>
                    <a href="/details?symbol=<?php echo $stock['symbol']; ?>">
                      <?php echo $stock['symbol']; ?>
                    </a>
                  </td>
                  <td>
                    <a href="/details?symbol=<?php echo $stock['symbol']; ?>">
                      <?php echo $stock['stock_name']; ?>
                    </a>
                  </td>
                  <td>
                    <a href="/details?symbol=<?php echo $stock['symbol']; ?>">
                      <?php echo $stock['exchange_name']; ?>
                    </a>
                  </td>
                </tr>
<?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </header>